# -*-coding:utf-8-*-

import paho.mqtt.client as mqtt

from src.MQTTHandler import MQTTHandler
from src.utils.log import log


class Mqtt:
    def __init__(self, broker='192.168.24.132', port=1883, client_id='ozx',
                 username='admin', password='OuZhenXian3762', userdata=None):
        # mqtt配置
        self.broker = broker
        self.port = port
        self.client_id = client_id
        self.username = username
        self.password = password
        self.userdata = userdata
        self.client: mqtt.Client = None
        self.handler = MQTTHandler()

        # 初始化日志
        self.log = log

        # 初始化mqtt
        self.get_mqtt(self.userdata)

    def on_connect(self, client: mqtt.Client, userdata, flags, rc):
        """连接成功回调函数"""
        if rc == 0:
            self.log.info(f"mqtt连接成功")
        else:
            self.log.error(f"mqtt连接失败: {rc}")

    def on_disconnect(self, client: mqtt.Client, userdata, rc):
        """断开连接回调函数"""
        if rc != 0:
            self.log.error(f"mqtt断开连接: {rc}")

    def on_subscribe(self, client, userdata, mid, granted_qos):
        """订阅主题回调函数"""
        pass
        # self.log.info(f"已订阅主题，消息 ID: {mid}")

    def on_publish(self, client, userdata, mid):
        """发布消息回调函数"""
        pass
        # self.log.info(f"已发布主题，消息 ID: {mid}")

    def on_message(self, client, userdata, msg):
        """接收消息回调函数"""
        self.log.info(f"已收到消息: {msg.payload.decode()}")

    def get_mqtt(self, userdata=None):
        """获取mqtt，并初始化配置"""
        self.client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION1,
                                  client_id=self.client_id, userdata=userdata)
        self.client.username_pw_set(self.username, self.password)
        self.client.on_connect = self.on_connect
        self.client.on_disconnect = self.on_disconnect
        self.client.on_subscribe = self.on_subscribe
        self.client.on_publish = self.on_publish
        self.client.on_message = self.handler.handleStrMsgCallback
        # 添加其他回调函数...

        try:
            self.client.connect(self.broker, self.port, keepalive=60)
        except Exception as e:
            self.log.error(f"mqtt连接失败: {e}")

    def publish(self, topic, payload, qos=0, retain=False):
        """发布主题"""
        result = self.client.publish(topic, payload, qos, retain)
        if result.rc == mqtt.MQTT_ERR_SUCCESS:
            self.log.info(f"消息已发布到主题 {topic}，消息 ID: {result.mid}")
        else:
            self.log.error(f"消息发布失败，错误码: {result.rc}")
            raise Exception(f"消息发布失败，错误码: {result.rc}")

    def subscribe(self, topic, qos=0):
        """订阅主题"""
        result, mid = self.client.subscribe(topic, qos)
        if result == mqtt.MQTT_ERR_SUCCESS:
            self.log.info(f"已订阅主题 {topic}，消息 ID: {mid}")
        else:
            self.log.error(f"订阅失败，错误码: {result}")
            raise Exception(f"订阅失败，错误码: {result}")

    #
    def loop_start(self):
        """ 启动mqtt线程(监听消息"""
        self.client.loop_start()

    def loop_stop(self):
        """ 停止mqtt线程"""
        self.client.loop_stop()
